package com.mes.handler;

import com.eam.data.EamCheckPlan;
import com.eam.data.EamCheckPlanFacilities;
import com.eam.data.EamCheckPlanItem;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import java.util.List;
import java.util.Map;

/**
 * 点检计划取消按钮
 * @author zt
 */
public class CheckCancelHandler extends BaseActionHandler {
	@SuppressWarnings("unchecked")
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject jsonRep = new JSONObject();
		String meg = "";
		try {
			OBContext.setAdminMode();
			String jsonIds = new JSONObject(content).getString("ids");
			// 获取勾选的点检计划
			String[] ids = jsonIds.split("#####");
			String status = "CANCEL";
			for (String id : ids) {
				EamCheckPlan checkplan = OBDal.getInstance().get(EamCheckPlan.class, id);
				//将点检计划状态改为已取消
				checkplan.setState(status);
				OBDal.getInstance().save(checkplan);
				String sql = "select * from Eam_Check_Plan_Facilities where Eam_Check_Plan_id = ? ";
				//获取点检计划下的点检设备
				List<EamCheckPlanFacilities> list = (List<EamCheckPlanFacilities>) OBDal.getInstance().getSession()
						.createSQLQuery(sql).addEntity(EamCheckPlanFacilities.ENTITY_NAME).setString(0, id).list();
				for (EamCheckPlanFacilities frequency : list) {
					EamCheckPlanFacilities checkitem = OBDal.getInstance().get(EamCheckPlanFacilities.class,
							frequency.getId());
					//将点检设备状态改为已取消
					checkitem.setStatus(status);
					OBDal.getInstance().save(checkitem);
					String wql = "select * from Eam_Check_Plan_Item where Eam_Facilities_run_item_id = ? ";
					List<EamCheckPlanItem> checkxm = (List<EamCheckPlanItem>) OBDal.getInstance()
							.getSession().createSQLQuery(wql).addEntity(EamCheckPlanItem.ENTITY_NAME)
							.setString(0, checkitem.getId()).list();
					for (EamCheckPlanItem detail : checkxm) {
						EamCheckPlanItem checkdetail = OBDal.getInstance().get(EamCheckPlanItem.class,
								detail.getId());
						//讲点检项目状态改为已取消
						checkdetail.setStatus(status);
						OBDal.getInstance().save(checkdetail);
					}
				}
			}
			if (meg.equalsIgnoreCase("")) {
				jsonRep.put("flag", true);
				jsonRep.put("message", "处理成功");
				OBDal.getInstance().commitAndClose();
			} else {
				jsonRep.put("flag", false);
				jsonRep.put("message", meg);
				OBDal.getInstance().rollbackAndClose();
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}
}
